package com.kb.design.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.util.StringUtil;
import com.kb.design.constant.Constants;
import com.kb.design.entity.CustomUser;
import com.kb.design.entity.DesignDept;
import com.kb.design.entity.UserSecurity;
import com.kb.design.enums.DesignStatus;
import com.kb.design.mapper.postgreSQL.CustomUserMapper;
import com.kb.design.mapper.postgreSQL.DesignDeptMapper;
import com.kb.design.service.DeptService;
import com.kb.design.util.Convert;
import com.kb.design.util.StringUtils;
import com.kb.design.vo.DesignDeptVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Auther:chenzx
 * @Date:2024-04-01
 * @Description:
 */
@Service
@DS("slave-1")
public class DeptServiceImpl  extends ServiceImpl<DesignDeptMapper, DesignDept> implements DeptService {

    @Resource
     private  DesignDeptMapper designDeptMapper;
    @Resource
    private CustomUserMapper userMapper;
    @Override
    public List<DesignDeptVO> selectDeptList(DesignDept dept) {
        List<DesignDeptVO> datas = new ArrayList<>();
        LambdaQueryWrapper<DesignDept> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(DesignDept::getDelFlag,"0").orderByAsc(DesignDept::getOrderNum);
        //查询条件
        queryWrapper.eq(StringUtils.isNotEmpty(dept.getStatus()),DesignDept::getStatus,dept.getStatus());
        queryWrapper.like(StringUtils.isNotEmpty(dept.getDeptName()),DesignDept::getDeptName,dept.getDeptName());

        List<DesignDept> designDepts = designDeptMapper.selectList(queryWrapper);
        // 如果查询结果不为空，补充查询其祖先部门
        if (CollUtil.isNotEmpty(designDepts)) {
            //判断designDepts是否没有id=0的父部门  针对条件查询返回没有数据的处理
            List<DesignDept> list = designDepts.stream().filter(t -> t.getParentId().equals(0L)).toList();
            if (list.isEmpty()) {
                Set<Long> ancestorIds = new HashSet<>();
                for (DesignDept designDept : designDepts) {
                    if (StringUtils.isNotEmpty(designDept.getAncestors())) {
                        String[] ancestors = designDept.getAncestors().split(",");
                        for (String ancestor : ancestors) {
                            if (StringUtils.isNotEmpty(ancestor)) {
                                ancestorIds.add(Long.valueOf(ancestor));
                            }
                        }
                    }
                }
                // 查询祖先部门
                if (!ancestorIds.isEmpty()) {
                    LambdaQueryWrapper<DesignDept> ancestorQueryWrapper = Wrappers.lambdaQuery();
                    ancestorQueryWrapper.in(DesignDept::getDeptId, ancestorIds);
                    List<DesignDept> ancestorDepts = designDeptMapper.selectList(ancestorQueryWrapper);
                    designDepts.addAll(ancestorDepts);
                }
                // 去重处理
                designDepts = designDepts.stream().collect(Collectors.collectingAndThen(
                        Collectors.toCollection(LinkedHashSet::new), ArrayList::new));
            }

            // 数据转换
            List<DesignDeptVO> designDeptVOList = designDepts.stream().map(info -> {
                DesignDeptVO designDeptVO = new DesignDeptVO();
                BeanUtils.copyProperties(info, designDeptVO);
                return designDeptVO;
            }).collect(Collectors.toList());

            // 构建树结构
            designDeptVOList.forEach(e -> {
                List<DesignDeptVO> childrenList = getChildrenList(e.getDeptId(), designDeptVOList);
                e.setChildren(CollectionUtil.isNotEmpty(childrenList) ? childrenList : null);
            });

            // 获取所有顶级节点
            List<DesignDeptVO> siteDtoParents = designDeptVOList.stream().filter(t -> t.getParentId().equals(0L)).toList();
            datas.addAll(siteDtoParents);
        }

        return datas;
    }

    @Override
    public List<DesignDept> queryArea() {
        //查询所有部门
        List<DesignDept> designDeptList = designDeptMapper.selectList(Wrappers.lambdaQuery(DesignDept.class)
                .eq(DesignDept::getStatus, Constants.DEL_FLAG_NO)
                //dept_functions字段不为空和null
                .isNotNull(DesignDept::getDeptFunctions)
        );
        return designDeptList;
    }

    @Override
    public List<DesignDept> getDeptById(DesignDept dept) {
        LambdaQueryWrapper<DesignDept> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(DesignDept::getDelFlag, Constants.DEL_FLAG_NO);
        if (dept.getParentId() != null){
            queryWrapper.eq(DesignDept::getParentId,dept.getParentId());
        }
        queryWrapper.eq(Objects.nonNull(dept.getDeptId()),DesignDept::getDeptId,dept.getDeptId());

        if (dept.getDeptFunctions() != null){
            //4代表全部
            if (Objects.equals(dept.getDeptFunctions(),"4")){
                queryWrapper.isNotNull(DesignDept::getDeptFunctions)
                            .ne(DesignDept::getDeptFunctions, "");
            }else {
                queryWrapper.eq(DesignDept::getDeptFunctions,dept.getDeptFunctions());
            }
        }
        List<DesignDept> designDepts = designDeptMapper.selectList(queryWrapper);
        if (CollectionUtil.isNotEmpty(designDepts)){
            //去除 部门含有 客服 字段的数据
            designDepts = designDepts.stream().filter(e -> !e.getDeptName().contains("客服")).collect(Collectors.toList());
        }
        return designDepts;
    }

    @Override
    public List<DesignDept> querySecondaryDept() {
        LambdaQueryWrapper<DesignDept> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(DesignDept::getDelFlag,Constants.DEL_FLAG_NO)
                .eq(DesignDept::getLevel,3)
                .eq(DesignDept::getQueryDept,1)
                .orderByAsc(DesignDept::getOrderNum);
        return designDeptMapper.selectList(queryWrapper);
    }

    @Override
    public List<DesignDept> queryDepartmentScreening(DesignDept dept) {
        LambdaQueryWrapper<DesignDept> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(DesignDept::getDelFlag,Constants.DEL_FLAG_NO);
        //启动项目 封装分配
        if (dept.getType().equals(1) && (dept.getStatus() == null || dept.getStatus().equals(DesignStatus.ENCAPSULATION.getIndex()))){
            queryWrapper.eq(DesignDept::getDeptFunctions,"1");
        }
        //设计分配
        if (dept.getStatus() != null){
            if (dept.getType().equals(1) && dept.getStatus().equals(DesignStatus.DESIGN.getIndex())){
                queryWrapper.eq(DesignDept::getDeptFunctions,"2");
            }
        }
        //封装完成
        if (dept.getType().equals(2)){
            queryWrapper.eq(DesignDept::getDeptFunctions,"2");
        }
        return designDeptMapper.selectList(queryWrapper);
    }

    @Override
    public List<DesignDeptVO> queryDailyDepartment(DesignDept dept) {
        List<DesignDeptVO> datas = new ArrayList<>();
        LambdaQueryWrapper<DesignDept> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(DesignDept::getDelFlag,"0");

        List<DesignDept> designDepts = designDeptMapper.selectList(queryWrapper);

        // 如果查询结果不为空，补充查询其祖先部门
        if (CollUtil.isNotEmpty(designDepts)) {
            // 数据转换
            List<DesignDeptVO> designDeptVOList = designDepts.stream().map(info -> {
                DesignDeptVO designDeptVO = new DesignDeptVO();
                BeanUtils.copyProperties(info, designDeptVO);
                return designDeptVO;
            }).collect(Collectors.toList());

            // 构建树结构
            designDeptVOList.forEach(e -> {
                List<DesignDeptVO> childrenList = getChildrenList(e.getDeptId(), designDeptVOList);
                e.setChildren(CollectionUtil.isNotEmpty(childrenList) ? childrenList : null);
            });

            //过滤部门 只需要 level = 3的部门及其下子部门
            List<DesignDeptVO> siteDtoParents = designDeptVOList.stream().filter(t -> t.getLevel().equals(3) && t.getDeptName().contains("设计中心")).toList();
            datas.addAll(siteDtoParents);
        }
        return datas;
    }

    @Override
    public void insertDept(DesignDept dept) {
        DesignDept info = designDeptMapper.selectById(dept.getParentId());
        // 如果父节点不为"正常"状态,则不允许新增子节点
        if (!Constants.DEPT_NORMAL.equals(info.getStatus()))
        {
            throw new RuntimeException("部门停用，不允许新增");
        }
        String leader = dept.getLeader();
        CustomUser user = userMapper.queryUserByCode(leader);
        if (user != null){
            dept.setLeaderName(user.getName());
        }
        dept.setAncestors(info.getAncestors() + "," + dept.getParentId());
        //层级计算 根据父级部门层级计算 newAncestors以，分割成list
        List<String> newAncestorsList = Arrays.asList(dept.getAncestors().split(","));
        dept.setLevel(newAncestorsList.size());
        designDeptMapper.insert(dept);
    }

    @Override
    public List<DesignDept> isDeptLeader(String userCode) {
            LambdaQueryWrapper<DesignDept> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.eq(DesignDept::getLeader,userCode);
            queryWrapper.eq(DesignDept::getDelFlag,"0");
        return designDeptMapper.selectList(queryWrapper);
    }

    @Override
    public long selectDeptCount(Long parentId) {
        LambdaQueryWrapper<DesignDept> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(DesignDept::getParentId,parentId);
        queryWrapper.eq(DesignDept::getDelFlag,"0");
        return designDeptMapper.selectCount(queryWrapper);
    }
    @Override
    public long deleteDeptById(Long deptId) {
        DesignDept designDept = new DesignDept();
        designDept.setDelFlag("1");
        designDept.setDeptId(deptId);
        return designDeptMapper.updateById(designDept);
    }

    @Override
    public boolean checkDeptNameUnique(DesignDept dept) {
        Long deptId = Objects.isNull(dept.getDeptId()) ? -1L : dept.getDeptId();
        LambdaQueryWrapper<DesignDept> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(DesignDept::getDeptName,dept.getDeptName()).eq(DesignDept::getParentId,dept.getDeptId()).eq(DesignDept::getDelFlag,"0");
        DesignDept info = designDeptMapper.selectOne(queryWrapper);

        if (StringUtils.isNotNull(info) && info.getDeptId().longValue() != deptId.longValue())
        {
            return Constants.NOT_UNIQUE;
        }
        return Constants.UNIQUE;
    }

    @Override
    public int selectNormalChildrenDeptById(Long deptId) {
        return 0;
    }

    @Override
    public int updateDept(DesignDept dept) {
        String leader = dept.getLeader();
        if (StringUtils.isNotEmpty(leader)) {
            CustomUser user = userMapper.queryUserByCode(leader);
            if (user != null){
                dept.setLeaderName(user.getName());
            }
        }else {
            dept.setLeaderName(null);
        }
        //更新用户里面的 部门名称
        LambdaUpdateWrapper<CustomUser> update = Wrappers.lambdaUpdate();
        update.eq(CustomUser::getDeptId,dept.getDeptId());
        CustomUser userUpdate = new CustomUser();
        userUpdate.setDeptName(dept.getDeptName());
        userMapper.update(userUpdate,update);

        DesignDept newParentDept = designDeptMapper.selectDeptById(dept.getParentId());
        DesignDept oldDept = selectDeptById(dept.getDeptId());
        if (StringUtils.isNotNull(newParentDept) && StringUtils.isNotNull(oldDept))
        {
            String newAncestors = newParentDept.getAncestors() + "," + newParentDept.getDeptId();
            String oldAncestors = oldDept.getAncestors();
            dept.setAncestors(newAncestors);
            updateDeptChildren(dept.getDeptId(), newAncestors, oldAncestors);
            //层级计算 根据父级部门层级计算 newAncestors以，分割成list
            List<String> newAncestorsList = Arrays.asList(newAncestors.split(","));
            dept.setLevel(newAncestorsList.size());
        }
        int result = designDeptMapper.updateDept(dept);
        if ("0".equals(dept.getStatus()) && StringUtils.isNotEmpty(dept.getAncestors())
                && !StringUtils.equals("0", dept.getAncestors()))
        {
            // 如果该部门是启用状态，则启用该部门的所有上级部门
            updateParentDeptStatusNormal(dept);
        }
        return result;
    }
    /**
     * 修改该部门的父级部门状态
     *
     * @param dept 当前部门
     */
    private void updateParentDeptStatusNormal(DesignDept dept)
    {
        String ancestors = dept.getAncestors();
        Long[] deptIds = Convert.toLongArray(ancestors);
        designDeptMapper.updateDeptStatusNormal(deptIds);
    }
    /**
     * 修改子元素关系
     *
     * @param deptId 被修改的部门ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateDeptChildren(Long deptId, String newAncestors, String oldAncestors)
    {
        List<DesignDept> children = designDeptMapper.selectChildrenDeptById(deptId);
        for (DesignDept child : children)
        {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        if (children.size() > 0)
        {
            designDeptMapper.updateDeptChildren(children);
        }
    }

    @Override
    public List<DesignDept> queryLeader(String code) {
        LambdaQueryWrapper<DesignDept> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(DesignDept::getLeader, code)
                .eq(DesignDept::getDelFlag, Constants.DEL_FLAG_NO);

        List<DesignDept> directDepts = designDeptMapper.selectList(queryWrapper);

        // 获取所有子部门
        List<DesignDept> allDepts = new ArrayList<>();
        if (!CollectionUtils.isEmpty(directDepts)){
            for (DesignDept dept : directDepts) {
                getAllSubDepts(dept, allDepts);
            }
        }

        return allDepts;
    }

    /**
     * 根本传入部门 查询所有的子部门
     * @param directDepts
     * @return
     */
    @Override
    public List<DesignDept> queryAllDept(Long deptId) {
        // 获取所有子部门
        List<DesignDept> allDepts = new ArrayList<>();
        DesignDept designDept = new DesignDept();
        designDept.setDeptId(deptId);
        getAllSubDepts(designDept, allDepts);
        return allDepts;
    }

    @Override
    public List<CustomUser> queryUserByDept(Long deptId) {
        // 查询部门下的所有用户
        return designDeptMapper.selectUsersByDeptAndChildren(deptId);
    }

    @Override
    public boolean checkDeptExistUser(Long deptId) {
            int result = designDeptMapper.checkDeptExistUser(deptId);
            return result > 0;
        }

    @Override
    public Integer selectUsersPinByDeptAndChildren(Long deptId) {
        return designDeptMapper.selectUsersPinByDeptAndChildren(deptId);
    }

    @Override
    public DesignDept selectDeptById(Long deptId) {
        return designDeptMapper.selectDeptById(deptId);
    }

    // 递归获取所有子部门
    private void getAllSubDepts(DesignDept currentDept, List<DesignDept> result) {
        if (currentDept == null) return;
        result.add(currentDept);

        // 查询当前部门的所有子部门
        LambdaQueryWrapper<DesignDept> childWrapper = Wrappers.lambdaQuery();
        childWrapper.eq(DesignDept::getParentId, currentDept.getDeptId())
                .eq(DesignDept::getDelFlag, Constants.DEL_FLAG_NO);

        List<DesignDept> children = designDeptMapper.selectList(childWrapper);
        for (DesignDept child : children) {
            getAllSubDepts(child, result); // 递归调用
        }
    }
    //获取全部的子集合
    public static List<DesignDeptVO> getChildrenList(Long id,List<DesignDeptVO> list){
        //便利全部数据，将需要的数据过滤出来
        return list.stream().filter(t-> t.getParentId().equals(id)).collect(Collectors.toList());
    }

}
